package com.yj.timecapsule.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.Date;

@Component
@Slf4j
public class OssUtil {
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.endpoint}")
    private String endpoint;

    public String upload(String fileName, String filePath) {
        // 创建OSSClient实例。
        OSS ossClient = getOssClient();
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, new File(filePath));

            // 执行上传操作
            ossClient.putObject(putObjectRequest);
            // 生成文件的公开URL（如果需要的话）
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000); // URL有效期1小时
            URL url = ossClient.generatePresignedUrl(bucket, fileName, expiration);
            log.info("上传成功 url:{}",url);
            // 上传成功后删除本地文件
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
            return url.toString();

            // 关闭OSSClient
        }catch (Exception e) {
            // 日志记录异常信息，根据实际情况处理
            log.error("文件上传失败 ", e);
            throw new BusinessException(ErrorCode.FILE_UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
    public OSS getOssClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }






}
